package com.hulu.yec.qes.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.hulu.yec.common.Constant;
import com.hulu.yec.common.util.AppUtil;
import com.hulu.yec.common.util.FastjsonUtil;
import com.hulu.yec.common.util.LogUtil;
import com.hulu.yec.qes.entity.QesPaperEntity;
import com.hulu.yec.qes.service.QesPaperService;
import com.hulu.yec.teach.testquestion.enetity.QuestionEntity;

/**
 * Servlet implementation class QesPaperServlet
 */
@WebServlet("/qes/QesPaperServlet")
public class QesPaperServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger(QesExamPaperServlet.class);
	QesPaperService qesPaperService = new QesPaperService();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		   doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constant.ENCODING_UTF8);
		String command = request.getParameter("command");
		if("preview".equals(command)){
			  preview(request,response);
		}else if("buildpaper".equals(command)){
			buildpaper(request,response);
			
			
		}
		
	}
	/**
	 * 预览
	 * @param request
	 * @param response
	 */
	private void preview(HttpServletRequest request,
			HttpServletResponse response) {
		String paperIdStr = request.getParameter("id");
		String paperName = request.getParameter("name");
		String paperPath = "D:/yuntu-1/paper/";
		File file = new File(paperPath+paperName + "-" + paperIdStr + ".txt");
		Reader reader = null;
		InputStream inputStream = null;
		StringBuilder sb = new StringBuilder();
		try{
			inputStream = new FileInputStream(file);
			reader = new InputStreamReader(inputStream);
			int count = 0;
			while((count = reader.read()) != -1){
				if(((char)count) != '\r'){
					sb.append((char)count);
				}
			}
			String paperJson = sb.toString();
			
			//将json转化成java对象
			@SuppressWarnings("rawtypes")
			List list = (List)FastjsonUtil.parseArray(paperJson, List.class);
			//全部单选题的集合
			List<QuestionEntity> sQuestions = new ArrayList<QuestionEntity>();
			//全部多选题的集合
			List<QuestionEntity> mQuestions = new ArrayList<QuestionEntity>();
			//全部判断题的集合
			List<QuestionEntity> jQuestions = new ArrayList<QuestionEntity>();
			
			//for(int i = 0;i < list.size();i++){
				//遍历出单选题
				@SuppressWarnings("unchecked")
				List<Object> slist = (List<Object>)list.get(0);
				System.out.println(Arrays.asList(slist));
				for(int j = 0; j < slist.size(); j++){
					//将获得的键值对用map存储
					@SuppressWarnings("unchecked")
					Map<String,Object> qesQestionsEntity = (Map<String, Object>) slist.get(j);
					QuestionEntity sentity = new QuestionEntity(
							(String)qesQestionsEntity.get("question"),
							(String)qesQestionsEntity.get("answer_a"),
							(String)qesQestionsEntity.get("answer_b"),
							(String)qesQestionsEntity.get("answer_c"),
							(String)qesQestionsEntity.get("answer_d")
							);
					//添加到题目的集合中
					sQuestions.add(sentity);
				}
				
				//遍历多选题
				@SuppressWarnings("unchecked")
				List<Object> mlist = (List<Object>)list.get(1);
				for(int j = 0; j < mlist.size(); j++){
					//将获得的键值对用map存储
					@SuppressWarnings("unchecked")
					Map<String,Object> qesQestionsEntity = (Map<String, Object>) mlist.get(j);
					QuestionEntity sentity = new QuestionEntity(
							(String)qesQestionsEntity.get("question"),
							(String)qesQestionsEntity.get("answer_a"),
							(String)qesQestionsEntity.get("answer_b"),
							(String)qesQestionsEntity.get("answer_c"),
							(String)qesQestionsEntity.get("answer_d")
							);
					mQuestions.add(sentity);
				}
				//遍历判断题
				@SuppressWarnings("unchecked")
				List<Object> jlist = (List<Object>)list.get(2);
				for(int j = 0; j < jlist.size(); j++){
					//将获得的键值对用map存储
					@SuppressWarnings("unchecked")
					Map<String,Object> qesQestionsEntity = (Map<String, Object>) jlist.get(j);
					QuestionEntity sentity = new QuestionEntity(
							(String)qesQestionsEntity.get("question"),
							(String)qesQestionsEntity.get("answer_a"),
							(String)qesQestionsEntity.get("answer_b"),
							(String)qesQestionsEntity.get("answer_c"),
							(String)qesQestionsEntity.get("answer_d")
							);
					jQuestions.add(sentity);
				}
				
			request.setAttribute("sQuestions", sQuestions);
			request.setAttribute("mQuestions", mQuestions);
			request.setAttribute("jQuestions", jQuestions);
				
			
			QesPaperEntity qesPaperEntity = qesPaperService.detailselect(Integer.parseInt(paperIdStr));
			
			request.setAttribute("qesPaperEntity", qesPaperEntity);
			request.setAttribute("paperName", paperName);
			request.setAttribute("paperJson", paperJson);
			request.getRequestDispatcher("/WEB-INF/view/stu/paper.jsp").forward(request, response);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}finally{
			try{
				if(inputStream!= null){
					inputStream.close();
				}
				if(reader != null){
					reader.close();
				}
			} catch (IOException e) {
			}
		}
	}
	

//	private void preview(HttpServletRequest request,
//			HttpServletResponse response) {
//		String paperIdStr = request.getParameter("id");
//		String paperName = request.getParameter("name");
//		System.out.println("id :"+paperIdStr+",name: "+paperName);
//		String paperPath = "D:/yuntu-1/paper/";
//		File file = new File(paperPath+paperName + "-" + paperIdStr + ".txt");
//		Reader reader = null;
//		InputStream inputStream = null;
//		StringBuilder sb = new StringBuilder();
//	
//			try {
//				inputStream = new FileInputStream(file);
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			reader = new InputStreamReader(inputStream);
//			int count = 0;
//			try {
//				while((count = reader.read()) !=-1){
//					if(((char)count) != '\r'){
//						sb.append((char)count);
//					}
//					
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			String paperJson = sb.toString();
//			//将json转化成java对象
//			List list = (List)FastjsonUtil.parseArray(paperJson, List.class);
//			//全部单选题的集合
//			List<QuestionEntity> choiceList = new ArrayList<QuestionEntity>();
//			//全部多选题的集合
//			List<QuestionEntity> multipleList = new ArrayList<QuestionEntity>();
//			//全部判断题的集合
//			List<QuestionEntity> judgeList = new ArrayList<QuestionEntity>();
//			
//
//			//遍历出单选题
//			@SuppressWarnings("unchecked")
//			List<Object> slist = (List<Object>)list.get(0);
//			for(int j = 0; j < slist.size(); j++){
//				//将获得的键值对用map存储
//				@SuppressWarnings("unchecked")
//				Map<String,Object> qesQestionsEntity = (Map<String, Object>) slist.get(j);
//				QuestionEntity choiceLists = new QuestionEntity(
//						(String)qesQestionsEntity.get("question"),
//						(String)qesQestionsEntity.get("answerA"),
//						(String)qesQestionsEntity.get("answerB"),
//						(String)qesQestionsEntity.get("answerC"),
//						(String)qesQestionsEntity.get("answerD")
//						);
//				//添加到题目的集合中
//				choiceList.add(choiceLists);
//			}
//			//遍历多选题
//			@SuppressWarnings("unchecked")
//			List<Object> mlist = (List<Object>)list.get(1);
//			for(int j = 0; j < mlist.size(); j++){
//				//将获得的键值对用map存储
//				@SuppressWarnings("unchecked")
//				Map<String,Object> qesQestionsEntity = (Map<String, Object>) mlist.get(j);
//				QuestionEntity multipleLists = new QuestionEntity(
//						(String)qesQestionsEntity.get("question"),
//						(String)qesQestionsEntity.get("answerA"),
//						(String)qesQestionsEntity.get("answerB"),
//						(String)qesQestionsEntity.get("answerC"),
//						(String)qesQestionsEntity.get("answerD")
//						);
//				multipleList.add(multipleLists);
//			}
//			//遍历判断题
//			@SuppressWarnings("unchecked")
//			List<Object> jlist = (List<Object>)list.get(2);
//			for(int j = 0; j < jlist.size(); j++){
//				//将获得的键值对用map存储
//				@SuppressWarnings("unchecked")
//				Map<String,Object> qesQestionsEntity = (Map<String, Object>) jlist.get(j);
//				QuestionEntity judgeLists = new QuestionEntity(
//						(String)qesQestionsEntity.get("question"),
//						(String)qesQestionsEntity.get("answerA"),
//						(String)qesQestionsEntity.get("answerB"),
//						(String)qesQestionsEntity.get("answerC"),
//						(String)qesQestionsEntity.get("answerD")
//						);
//				judgeList.add(judgeLists);
//			}
//			request.setAttribute("choiceList", choiceList);
//			request.setAttribute("multipleList", multipleList);
//			request.setAttribute("judgeList", judgeList);
//			
//            QesPaperEntity qesPaperEntity = qesPaperService.detailselect(Integer.parseInt(paperIdStr));
//			
//			request.setAttribute("qesPaperEntity", qesPaperEntity);
//			request.setAttribute("paperName", paperName);
//			request.setAttribute("paperJson", paperJson);
//			try {
//				request.getRequestDispatcher("/WEB-INF/view/stu/paper.jsp").forward(request, response);
//			} catch (ServletException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
				
		
	
	//}
	//ajax试卷管理查询页面的试卷生成
//		private void buildpaper(HttpServletRequest request,
//				HttpServletResponse response) {
//				String paperIdStr = request.getParameter("id");
//				System.out.println("paperIdStr: "+paperIdStr);
//				if(paperIdStr == null){
//				}else{
//					int paperId = Integer.parseInt(paperIdStr);
//					QesPaperEntity paper = qesPaperService.detailselect(paperId);
//					
//					//根据试卷信息生成的题目的集合
//					List<QuestionEntity> singles = qesPaperService.getQestions(paper.getCourseId(),1,paper.getSingleOptionDifficulty(),paper.getSingleOptionNumber());
//					List<QuestionEntity> multis = qesPaperService.getQestions(paper.getCourseId(), 2, paper.getMultiOptionDifficulty(),paper.getMultiOptionNumber());
//					List<QuestionEntity> judges = qesPaperService.getQestions(paper.getCourseId(), 3, paper.getJudgeDifficulty(),paper.getJudgeNumber());
//					
//					
//					List<Object> myPaper = new ArrayList<Object>();
//					myPaper.add(singles);
//					myPaper.add(multis);
//					myPaper.add(judges);
//					
//					//生成json
//					String myPaperStr = FastjsonUtil.toJson(myPaper);
//					
//					byte[] myPaperbyte = myPaperStr.getBytes();
//					File file = null;
//					File dir = null;
//					FileOutputStream fileOutputStream = null;
//					//配置文件路径
//					dir = new File("D:/yuntu-1/paper/");
//					file = new File(dir,paper.getName()+"-"+paper.getId()+".txt");
//					if(!file.exists()){
//						dir.mkdirs();
//					}
//					
//					try {
//						fileOutputStream = new FileOutputStream(file);
//						fileOutputStream.write(myPaperbyte);
//						System.out.println("-------------");
//						//将文件路径添加到qes_exam_paper表中
//						qesPaperService.addPaperUrl(file.toString(),paperId);
//					} catch (FileNotFoundException e1) {
//						e1.printStackTrace();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}finally{
//						if(fileOutputStream != null){
//							try {
//								fileOutputStream.close();
//							} catch (IOException e) {
//								e.printStackTrace();
//							}
//						}
//					}
//					
//					PrintWriter  printWriter = null;
//					
//					try {
//						printWriter = response.getWriter();
//						printWriter.print("yes");
//					} catch (IOException e) {
//					}finally{
//						if(printWriter!=null){
//							printWriter.close();
//						}
//					}
//				}
//				
//		
//		} 
//	}
	
	//ajax试卷管理查询页面的试卷生成
		private void buildpaper(HttpServletRequest request,
				HttpServletResponse response) {String paperIdStr = request.getParameter("id");
				if(paperIdStr == null){
				}else{
					int paperId = Integer.parseInt(paperIdStr);
					QesPaperEntity paper = qesPaperService.detailselect(paperId);
					//根据试卷信息生成的题目的集合
					System.out.println(paper.getSingleOptionDifficulty());
					List<QuestionEntity> singles = qesPaperService.getQestions(1,paper.getSingleOptionNumber());
					List<QuestionEntity> multis = qesPaperService.getQestions(2, paper.getMultiOptionNumber());
					List<QuestionEntity> judges = qesPaperService.getQestions(3, paper.getJudgeNumber());
					List<Object> myPaper = new ArrayList<Object>();
					myPaper.add(singles);
					myPaper.add(multis);
					myPaper.add(judges);
					
					//生成json
					String myPaperStr = FastjsonUtil.toJson(myPaper);
					byte[] myPaperbyte = myPaperStr.getBytes();
					File file = null;
					File dir = null;
					FileOutputStream fileOutputStream = null;
					//配置文件路径
					dir = new File("D:/yuntu-1/paper/");
					file = new File(dir,paper.getName()+"-"+paper.getId()+".txt");
					if(!file.exists()){
						dir.mkdirs();
					}
					
					try {
						fileOutputStream = new FileOutputStream(file);
						fileOutputStream.write(myPaperbyte);
						//将文件路径添加到qes_exam_paper表中
						qesPaperService.addPaperUrl(file.toString(),paperId);
					} catch (FileNotFoundException e1) {
						e1.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}finally{
						if(fileOutputStream != null){
							try {
								fileOutputStream.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
					
					PrintWriter  printWriter = null;
					
					try {
						printWriter = response.getWriter();
						printWriter.print("yes");
					} catch (IOException e) {
						e.printStackTrace();
					}finally{
						if(printWriter!=null){
							printWriter.close();
						}
					}
				}
				
		}
	}





